#include "database.h"
#include <QDir>
#include <QStandardPaths>

Database::Database(QObject *parent)
    : QObject(parent)
{
    // 构造函数
}

Database::~Database()
{
    if (db.isOpen()) {
        db.close();
    }
}

bool Database::initDatabase()
{
    // 获取应用程序数据目录
    QString dataPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(dataPath);
    if (!dir.exists()) {
        dir.mkpath(dataPath);
    }
    
    // 设置数据库文件路径
    QString dbPath = dataPath + "/chat_history.db";
    
    // 创建数据库连接
    db = QSqlDatabase::addDatabase("QSQLITE", "ChatHistory");
    db.setDatabaseName(dbPath);
    
    if (!db.open()) {
        qDebug() << "数据库打开失败:" << db.lastError().text();
        return false;
    }
    
    // 创建数据表
    return createTables();
}

bool Database::createTables()
{
    QSqlQuery query(db);
    
    // 创建聊天记录表
    QString createTableSQL = 
        "CREATE TABLE IF NOT EXISTS chat_messages ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "sender TEXT NOT NULL,"
        "message TEXT NOT NULL,"
        "timestamp TEXT NOT NULL,"
        "created_at DATETIME DEFAULT CURRENT_TIMESTAMP"
        ")";
    
    if (!query.exec(createTableSQL)) {
        qDebug() << "创建表失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

bool Database::saveMessage(const QString &sender, const QString &message, const QString &timestamp)
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO chat_messages (sender, message, timestamp) VALUES (?, ?, ?)");
    query.addBindValue(sender);
    query.addBindValue(message);
    query.addBindValue(timestamp);
    
    if (!query.exec()) {
        qDebug() << "保存消息失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}

QStringList Database::loadHistory(int limit)
{
    QStringList history;
    QSqlQuery query(db);
    
    query.prepare("SELECT sender, message, timestamp FROM chat_messages "
                  "ORDER BY created_at DESC LIMIT ?");
    query.addBindValue(limit);
    
    if (query.exec()) {
        while (query.next()) {
            QString sender = query.value(0).toString();
            QString message = query.value(1).toString();
            QString timestamp = query.value(2).toString();
            
            QString historyItem = QString("[%1] %2: %3")
                                    .arg(timestamp)
                                    .arg(sender)
                                    .arg(message);
            history.prepend(historyItem); // 按时间顺序排列
        }
    } else {
        qDebug() << "加载历史记录失败:" << query.lastError().text();
    }
    
    return history;
}

bool Database::clearHistory()
{
    QSqlQuery query(db);
    
    if (!query.exec("DELETE FROM chat_messages")) {
        qDebug() << "清空历史记录失败:" << query.lastError().text();
        return false;
    }
    
    return true;
}
